/*
 * Created by Jaren at 2021/12/1 11:35
 */
import 'dart:async';
import 'dart:ffi';
import 'dart:typed_data';
import 'dart:io';

import 'package:binary/binary.dart';
import 'package:inmotion_protocol/base/base_factory.dart';
import 'package:inmotion_protocol/base/base_message.dart';
import 'package:inmotion_protocol/base/file/file_manager.dart';
import 'package:inmotion_protocol/base/protocol.dart';
import 'package:inmotion_protocol/base/vehicle_data.dart';
import 'package:inmotion_protocol/codec_holder.dart';
import 'package:inmotion_protocol/common/accessory_info.dart';
import 'package:inmotion_protocol/common/bms_log_manager.dart';
import 'package:inmotion_protocol/common/exceptions.dart';
import 'package:inmotion_protocol/common/fw_update_manager.dart';
import 'package:inmotion_protocol/common/log_file_manager.dart';
import 'package:inmotion_protocol/common/media_file_upload_manager.dart';
import 'package:inmotion_protocol/common/product_model.dart';
import 'package:inmotion_protocol/common/product_version.dart';
import 'package:inmotion_protocol/common/response.dart';
import 'package:inmotion_protocol/common/riding_statistics_helper.dart';
import 'package:inmotion_protocol/common/vehicle_info.dart';
import 'package:inmotion_protocol/elephant/codec.dart';
import 'package:inmotion_protocol/elephant/factory/message_factory.dart';
import 'package:inmotion_protocol/elephant/message.dart';
import 'package:inmotion_protocol/elephant/protocol.dart';
import 'package:inmotion_protocol/ezcan/bean/ebike/ebike_settings.dart';
import 'package:inmotion_protocol/ezcan/codec.dart';
import 'package:inmotion_protocol/ezcan/ezcan_message.dart';
import 'package:inmotion_protocol/ezcan/factory/ezcan_factory.dart';
import 'package:inmotion_protocol/ezcan/protocol.dart';
import 'package:inmotion_protocol/features.dart';
import 'package:inmotion_protocol/handler/send_handler.dart';
import 'package:inmotion_protocol/lorin/bean/base/bms_info.dart';
import 'package:inmotion_protocol/lorin/bean/base/tbox.dart';
import 'package:inmotion_protocol/lorin/bean/base/tire_pressure_sensor.dart';
import 'package:inmotion_protocol/lorin/bean/common/date.dart';
import 'package:inmotion_protocol/lorin/bean/common/response/response.dart';
import 'package:inmotion_protocol/lorin/bean/common/bms_info.dart';
import 'package:inmotion_protocol/lorin/bean/euc/v13/v13_statistics.dart';
import 'package:inmotion_protocol/lorin/codec.dart';
import 'package:inmotion_protocol/lorin/constant.dart';
import 'package:inmotion_protocol/lorin/factory/lorin_message_factory.dart';
import 'package:inmotion_protocol/lorin/lorin_message.dart';
import 'package:inmotion_protocol/lorin/media/avatar_file_manager.dart';
import 'package:inmotion_protocol/lorin/protocol.dart';
import 'package:inmotion_protocol/lorin/util.dart';
import 'package:inmotion_protocol/protocol_worker.dart';
import 'package:inmotion_protocol/util/device.dart';
import 'package:inmotion_protocol/util/log.dart';
import 'package:inmotion_protocol/util/version.dart';

class InMotionProtocol {
//    static const lorinProtocolDeviceNameRegex = "[V11|V12|L9|S1|A1|C1][\\S+]-[0-9A-Z]{8}";
//    static const ezCANProtocolDeviceNameRegex = "[V3|V5|V8|V10|L8|P1|P2][\\S+]-[0-9A-Z]{8}";
//    static const elephantProtocolDeviceNameRegex = "[E2|E3|R0][\\S+]-[0-9A-Z]{8}";

  static const lorinProtocolDeviceNamePrefix = [
    'V12S',
    'V9',
    'V11',
    'V12',
    'V13',
    'L9',
    'S1',
    'A1',
    'C1',
    'Air',
    'Climber',
    'RS',
    'Adventure',
    'E20',
    'E10',
    'E15',
    'P6',
    'E25',
    'V18',
    'V6',
  ];
  static const ezCANProtocolDeviceNamePrefix = [
    'V5',
    'V8',
    'V10',
    'L8',
    'P1',
    'P2',
    'Glide',
    'R1'
  ];
  static const elephantProtocolDeviceNamePrefix = ['E2', 'E3', 'R0'];

  static const lorinProtocolFlag = 1;
  static const ezCANProtocolFlag = 2;
  static const elephantProtocolFlag = 3;

  Protocol? _protocol;

  ProtocolWorker? _protocolWorker;

  // 清除mqqt的队列事件
  void clearMqqtEvent() {
    _protocolWorker?.mqqtFunctions.clear();
  }

  /// 协议库预初始化
  /// 依据[deviceName]或[protocolFlag]初始化协议类型
  void preInit(SendHandler sendHandler, int maxSizePeerPkg,
      {String? deviceName, int? protocolFlag}) {
    MsgFactory msgFactory;
    ProtocolType protocolType =
        parseProtocolType(deviceName: deviceName, protocolFlag: protocolFlag);
    if (protocolType == ProtocolType.lorin) {
      msgFactory = LorinMessageFactory();
      _protocolWorker = ProtocolWorker<LorinMessage>(sendHandler);
      CodecHolder.instance.putDecoder(LorinDecoder());
      CodecHolder.instance.putEncoder(LorinEncoder());
      _protocol = LorinProtocol(_protocolWorker as ProtocolWorker<LorinMessage>,
          msgFactory as LorinMessageFactory);
    } else if (protocolType == ProtocolType.ezCAN) {
      msgFactory = EzcanFactory();
      _protocolWorker = ProtocolWorker<EzcanMessage>(sendHandler);
      CodecHolder.instance.putDecoder(EzcanDecoder());
      CodecHolder.instance.putEncoder(EzcanEncoder());
      _protocol = EzCANProtocol(_protocolWorker as ProtocolWorker<EzcanMessage>,
          msgFactory as EzcanFactory);
    } else if (protocolType == ProtocolType.elephant) {
      msgFactory = ElephantMessageFactory();
      _protocolWorker = ProtocolWorker<ElephantMessage>(sendHandler);
      CodecHolder.instance.putDecoder(ElephantDecoder());
      CodecHolder.instance.putEncoder(ElephantEncoder());
      _protocol = ElephantProtocol(
          _protocolWorker as ProtocolWorker<ElephantMessage>,
          msgFactory as ElephantMessageFactory);
    } else {
      // can't reach
      throw NotSupportException('Not support protocol type.');
    }
    _protocol!.maxSizePeerPkg = maxSizePeerPkg;
    LogUtils.d("inmotion protocol, max size peer pkg set to $maxSizePeerPkg");
  }

  /// 协议库初始化
  /// 依据[model]和[version]对协议库内部协议版本进行初始化
  void init(ProductModel model, VersionWrapper version) {
    __protocol().setup(model, version);
  }

  /// 指定接收协议库内部未处理的消息处理器
  void setUnhandledMsgHandler(Function f) {
    __protocol().setUnhandledMsgHandler(f);
  }

  /// 通知协议库收到设备端数据
  void onDataReceived(Uint8ClampedList bytes, [String clientId = '']) {
    if (bytes.isEmpty) return;
    __protocol().onDataReceived(bytes, clientId);
  }

  /// 通知物理层已建立连接
  Future onLinkLayerConnected(String deviceName,
      {String clientId = '', bool resetData = true}) async {
    return Future(() async {
      await __protocol().prepareOnLinkLayerConnected(deviceName,
          clientId: clientId, resetData: resetData);
    });
  }

  /// 设置协议库日志等级
  void setLogLevel(LogLevel level) {
    LogUtils.level = level;
  }

  /// 请求云盒Esim卡列表
  Future<List<EsimModel>> requestTBoxEsimList() {
    return __protocol().requestTBoxEsimList();
  }

  /// 请求云盒信息
  Future<TBoxInfo> requestTBoxInfo() {
    return __protocol().requestTBoxInfo();
  }

  /// 请求云盒实时信息
  Future<TBoxInfo> requestTBoxRealTimeInfo() {
    return __protocol().requestTBoxRealTimeInfo();
  }

  /// 重启云盒
  Future<bool> rebootTBox(int mode) {
    return __protocol().rebootTBox(mode);
  }

  /// 获取初始信息[ProductProperty]
  /// 包含SN,ProductModel,VersionWrapper(仅包含软件版本)
  Future<ProductProperty> requestProductProperty() {
    return __protocol().requestProductProperty();
  }

  /// 获取初始信息[ProductProperty]
  /// 包含SN,ProductModel,VersionWrapper(仅包含软件版本),单条指令
  Future<ProductProperty> requestProductPropertyV2() {
    return __protocol().requestProductPropertyV2();
  }

  /// 获取车辆信息[VehicleInfo] 单条指令请求首页数据内容
  Future<VehicleSynthesizeRealTimeInfo> requestVehicleSynthesizeRealTimeInfo() {
    return __protocol().requestVehicleSynthesizeRealTimeInfo();
  }

  /// 请求全部实时信息[AllRealTimeData]
  /// 可将结果按实际转为各协议和车型的全部实时信息
  Future<AllRealTimeData> requestAllRealTimeData() {
    return __protocol().requestAllRealTimeData();
  }

  /// 请求实时信息
  Future<RealTimeInfo> requestRealTimeInfo() {
    return __protocol().requestRealTimeInfo();
  }

  /// 请求实时状态
  Future<RealTimeState> requestRealTimeState() {
    return __protocol().requestRealTimeState();
  }

  /// 请求实时故障和警告
  Future<RealTimeError> requestRealTimeError() {
    return __protocol().requestRealTimeError();
  }

  /// 请求历史统计信息
  /// 从[index]开始，获取[count]条单次统计信息
  Future<StatisticsResponse> requestHistoryStatistics(int index, int count) {
    return __protocol().requestHistoryStatistics(index, count);
  }

  /// 请求历史统计信息的信息
  /// see [StatisticsInfoResponse]
  Future<StatisticsInfoResponse> requestHistoryStatisticsInfo() {
    return __protocol().requestHistoryStatisticsInfo();
  }

  /// 请求当前统计信息
  Future<HistoryStatistics> requestCurrentStatistics() {
    return __protocol().requestCurrentStatistics();
  }

  /// 请求总统计信息
  Future<TotalStatistics> requestTotalStatistics() {
    return __protocol().requestTotalStatistics();
  }

  /// 请求电池实时信息
  Future<BatteryRealTimeInfo> requestBatteryRealTimeInfo() {
    return __protocol().requestBatteryRealTimeInfo();
  }

  /// 请求综合设置项数据
  Future<Settings> requestSettings() {
    return __protocol().requestSettings();
  }

  /// 请求获取激活时间
  Future<DateTime> requestActivatedTime() {
    return __protocol().requestActivatedTime();
  }

  /// 请求所有设备唯一ID信息
  Future<DeviceWrapper> requestDevicesId(List<int> devices) {
    return __protocol().requestDevicesId(devices);
  }

  /// 请求所有配件信息
  Future<AccessoryWrapper> requestAccessoriesInfo() {
    return __protocol().requestAccessoriesInfo();
  }

  /// 请求所有设备的固件版本
  Future<VersionWrapper> requestFwVersion([int? target]) {
    return __protocol().requestFwVersion(target);
  }

  /// 回复快速连接请求
  Future<void> respondQuickConnect() {
    return __protocol().respondQuickConnect();
  }

  /// 获取氛围灯模式
  Future<Uint8ClampedList> requestLightEffectMode() {
    return __protocol().requestLightEffectMode();
  }

  /// 设备丢失模式
  Future<SettingsResponse> lostMode([bool enable = true]) {
    return __protocol().lostMode(enable);
  }

  /// 校准RTC
  Future<bool> syncRTC([DateTime? dateTime]) {
    return __protocol().syncRTC(dateTime);
  }

  /// 激活车辆
  Future<bool> activate({DateTime? dateTime}) {
    dateTime ??= DateTime.now();
    return __protocol().activate(dateTime);
  }

  /// 设置双电池模式
  Future<SettingsResponse> setTwoBatteryMode([bool on = true]) {
    return __protocol().twoBatteryMode(on);
  }

  /// 设置自动前灯开关
  Future<SettingsResponse> setDaytimeRunningLightOnOff([bool on = true]) {
    return __protocol().daytimeRunningLightOnOff(on);
  }

  /// 设置自动前灯开关
  Future<SettingsResponse> autoHeadlightOnOff([bool on = true]) {
    return __protocol().autoHeadlightOnOff(on);
  }

  /// 设置自动息屏开关
  Future<SettingsResponse> autoScreenOffOnOff([bool on = true]) {
    return __protocol().autoScreenOffOnOff(on);
  }

  /// 启动校准
  /// [which] 校准类型
  Future<SettingsResponse> startCalibration(int which) {
    return __protocol().startCalibration(which);
  }

  /// 查询校准结果
  /// [which] 校准类型
  Future<AbsCalibrationResultResponse> queryCalibrationResult(int which) {
    return __protocol().queryCalibrationResult(which);
  }

  /// 设置定速巡航开关
  Future<SettingsResponse> cruiseOnOff([bool on = true]) {
    return __protocol().cruiseOnOff(on);
  }

  /// 设置风扇开关
  Future<SettingsResponse> fanOnOff([bool on = true]) {
    return __protocol().fanOnOff(on);
  }

  /// 设置风扇静音模式开关
  Future<SettingsResponse> fanQuietModeOnOff([bool on = true]) {
    return __protocol().fanQuietModeOnOff(on);
  }

  /// 设置上坡辅助开关
  Future<SettingsResponse> hacOnOff([bool on = true]) {
    return __protocol().hacOnOff(on);
  }

  /// 设置下坡辅助开关
  Future<SettingsResponse> hdcOnOff([bool on = true]) {
    return __protocol().hdcOnOff(on);
  }

  /// 设置氛围灯模式或开关
  Future<SettingsResponse> setLightEffectMode(
      {bool? onOff, int? mode, int? paramColor, int? paramMode}) {
    return __protocol().setLightEffectMode(
        onOff: onOff, mode: mode, paramColor: paramColor, paramMode: paramMode);
  }

  /// 设置前照灯开关
  Future<SettingsResponse> headlightOnOff(
      {bool? on, bool? lowBeamOn, bool? highBeamOn}) {
    return __protocol()
        .headlightOnOff(on: on, lowBeamOn: lowBeamOn, highBeamOn: highBeamOn);
  }

  /// 设置前照灯亮度
  Future<SettingsResponse> setHeadlightBrightness(
      {int? brightness, int? lowBeamBrightness, int? highBeamBrightness}) {
    return __protocol().setHeadlightBrightness(
        brightness: brightness,
        lowBeamBrightness: lowBeamBrightness,
        highBeamBrightness: highBeamBrightness);
  }

  /// 设置自动前照灯开关环境亮度阈值
  Future<SettingsResponse> setAutoHeadlightBrightnessThr(
      int lowThr, int highThr) {
    return __protocol().setAutoHeadlightBrightnessThr(lowThr, highThr);
  }

  /// 设置远近光自动灯切换开关
  Future<SettingsResponse> autoLowHighBeamOnOff([bool on = true]) {
    return __protocol().autoLowHighBeamOnOff(on);
  }

  /// 设置远近光灯自动切换速度阈值
  Future<SettingsResponse> setAutoLowHighBeamSwitchSpeedThr(int speedThr) {
    return __protocol().setAutoLowHighBeamSwitchSpeedThr(speedThr);
  }

  /// 设置负载检测开关
  Future<SettingsResponse> loadDetectOnOff([bool on = true]) {
    return __protocol().loadDetectOnOff(on);
  }

  /// 设置锁车开关
  Future<SettingsResponse> lock([bool lock = true]) {
    return __protocol().lock(lock);
  }

  /// 设置低电安全模式开关
  Future<SettingsResponse> lowBatLevelProtectionModeOnOff([bool on = true]) {
    return __protocol().lowBatLevelProtectionModeOnOff(on);
  }

  /// 设置云盒低电唤醒模式开关
  Future<SettingsResponse> tboxLowBatLevelWakeUpVehicleModeOnOff(
      [bool on = true]) {
    return __protocol().tboxLowBatLevelWakeUpVehicleModeOnOff(on);
  }

  /// 设置云盒信息在车辆上的显示与隐藏
  Future<SettingsResponse> showTboxInfoOnVehicleOnOff([bool on = true]) {
    return __protocol().showTboxInfoOnVehicleOnOff(on);
  }

  /// 设置空载检测开关
  Future<SettingsResponse> noLoadDetectOnOff([bool on = true]) {
    return __protocol().noLoadDetectOnOff(on);
  }

  /// 设置续航里程智能估算开关
  Future<SettingsResponse> remainderRangeEstimateOnOff([bool on = true]) {
    return __protocol().remainderRangeEstimateOnOff(on);
  }

  /// 设置安全限速模式开关
  Future<SettingsResponse> safeSpeedLimitOnOff([bool on = true]) {
    return __protocol().safeSpeedLimitOnOff(on);
  }

  /// 设置赛道倾角模式开关
  Future<SettingsResponse> bermAngleModeOnOff([bool on = true]) {
    return __protocol().bermAngleModeOnOff(on);
  }

  /// 设置EBike限速报警开关（国标超25km/h报警）
  Future<SettingsResponse> overSpeedWarningOnOff([bool on = true]) {
    return __protocol().overSpeedWarningOnOff(on);
  }

  /// 设置超速报警提示限速值
  /// V12两级报警
  Future<SettingsResponse> setWarningLimitSpeed(int speed1, int speed2) {
    return __protocol().setWarningLimitSpeed(speed1, speed2);
  }

  /// 绑定胎压传感器
  Future<bool> bindTirePressureSensor(String sensorId) {
    return __protocol().bindTirePressureSensor(sensorId);
  }

  /// 搜索胎压传感器
  Future<List<TirePressureSensor>> searchTirePressureSensor() {
    return __protocol().searchTirePressureSensor();
  }

  /// 重置胎压传感器搜索结果
  Future<SettingsResponse> resetTirePressureSensorSearchResult() {
    return __protocol().resetTirePressureSensorSearchResult();
  }

  /// 设置胎压报警开关
  Future<SettingsResponse> tirePressureWarningOnOff([bool on = true]) {
    return __protocol().tirePressureWarningOnOff(on);
  }

  /// 设置胎压报警阈值
  Future<SettingsResponse> setLowTirePressureWarningThreshold(
      int lowThreshold) {
    return __protocol().setLowTirePressureWarningThreshold(lowThreshold);
  }

  /// 设置logo灯亮度
  Future<SettingsResponse> setLogoLightBrightness(int brightness) {
    return __protocol().setLogoLightBrightness(brightness);
  }

  /// 设置转向灯模式
  Future<SettingsResponse> setTurnSignalMode(int mode) {
    return __protocol().setTurnSignalMode(mode);
  }

  /// 设置赛道倾斜角度
  Future<SettingsResponse> setBermAngle(int angle) {
    return __protocol().setBermAngle(angle);
  }

  /// 设置输出饱和阈值
  Future<SettingsResponse> setOutputThreshold(int tiltBack, int warning1, int warning2) {
    return __protocol().setOutputThreshold(tiltBack, warning1, warning2);
  }

  /// 设置辅助平衡模式开关
  Future<SettingsResponse> assistBalanceOnOff([bool on = true]) {
    return __protocol().assistBalanceOnOff(on);
  }

  /// 设置设备名称
  Future<SettingsResponse> setDeviceName(String name) {
    return __protocol().setDeviceName(name);
  }

  /// 设置驱动模式
  Future<SettingsResponse> setDriveMode(int mode) {
    return __protocol().setDriveMode(mode);
  }

  /// 设置灯效ID
  Future<SettingsResponse> setLightEffectId(int id, [int? color]) {
    return __protocol().setLightEffectId(id, color);
  }

  /// 设置设备密码
  Future<SettingsResponse> setPassword(String pwd, [int? type]) {
    return __protocol().setPassword(pwd, type);
  }

  /// 设置设备密码类型
  Future<SettingsResponse> setPasswordType(int type) {
    return __protocol().setPasswordType(type);
  }

  /// 设置踏板灵敏度
  /// 单位1%
  Future<SettingsResponse> setPedalSensitivity(int sensitivity,
      [int? sensitivity2]) {
    return __protocol().setPedalSensitivity(sensitivity, sensitivity2);
  }

  /// 设置平衡零点
  /// 单位0.01°
  Future<SettingsResponse> setPitchAngleZero(int angle) {
    return __protocol().setPitchAngleZero(angle);
  }

  /// 设置骑行模式
  Future<SettingsResponse> setRidingMode(int mode, [var param]) {
    return __protocol().setRidingMode(mode, param);
  }

  /// 设置助力模式
  Future<SettingsResponse> setAssistantMode(int mode, [var param]) {
    return __protocol().setAssistantMode(mode, param);
  }

  /// 设置音效包ID
  Future<SettingsResponse> setSoundPackId(int id) {
    return __protocol().setSoundPackId(id);
  }

  /// 设置主动声浪灵敏度
  Future<SettingsResponse> setSoundWaveSensitivity(int sensitivity) {
    return __protocol().setSoundWaveSensitivity(sensitivity);
  }

  /// 设置限速
  /// [speedLimit] 限速值
  /// [speedLimit2] 不为空时，[speedLimit]表示超速翘板值，[speedLimit2]表示超速报警值
  Future<SettingsResponse> setSpeedLimit(int speedLimit, [int? speedLimit2]) {
    return __protocol().setSpeedLimit(speedLimit, speedLimit2);
  }

  /// 设置行人模式限速
  Future<SettingsResponse> setSpeedLimitOfAssistMode(int speedLimit) {
    return __protocol().setSpeedLimitOfAssistMode(speedLimit);
  }

  /// 设置加速反馈和减速反馈值
  Future<SettingsResponse> setSpeedingBrakingSensitivity(
      int speeding, int braking) {
    return __protocol().setSpeedingBrakingSensitivity(speeding, braking);
  }

  /// 设置待机时间
  Future<SettingsResponse> setStandbyTime(int seconds) {
    return __protocol().setStandbyTime(seconds);
  }

  /// 设置音量大小
  Future<SettingsResponse> setVolume(int volume) {
    return __protocol().setVolume(volume);
  }

  /// 设置音效包开关
  Future<SettingsResponse> soundPackOnOff([bool on = true]) {
    return __protocol().soundPackOnOff(on);
  }

  /// 播放某条音效
  Future<SettingsResponse> playSoundItem(int index) {
    return __protocol().playSoundItem(index);
  }

  Future<SettingsResponse> horn() {
    return __protocol().horn();
  }

  /// 设置主动声浪开关
  Future<SettingsResponse> soundWaveOnOff([bool on = true]) {
    return __protocol().soundWaveOnOff(on);
  }

  /// 设置体感分离模式开关
  Future<SettingsResponse> speedingBrakingOnOff([bool on = true]) {
    return __protocol().speedingBrakingOnOff(on);
  }

  /// 设置防飞转开关
  Future<SettingsResponse> spinKillOnOff([bool on = true]) {
    return __protocol().spinKillOnOff(on);
  }

  /// 设置运输模式开关
  Future<SettingsResponse> transportationModeOnOff([bool on = true]) {
    return __protocol().transportationModeOnOff(on);
  }

  /// 设置USB开关
  Future<SettingsResponse> usbPowerOnOff([bool on = true]) {
    return __protocol().usbPowerOnOff(on);
  }

  /// 设置零速启动开关
  Future<SettingsResponse> zeroSpeedupOnOff(
      [bool on = true, AssistanceSettings? assistanceSettings]) {
    return __protocol().zeroSpeedupOnOff(on, assistanceSettings);
  }

  /// 设置公英制单位
  Future<SettingsResponse> setSpeedUnit(int speedUnit) {
    return __protocol().setSpeedUnit(speedUnit);
  }

  /// 关闭充电危险警告
  Future<SettingsResponse> disableChargeDangerAlert() {
    return __protocol().disableChargeDangerAlert();
  }

  /// 开关GPS
  Future<SettingsResponse> gpsOnOff([bool on = true]) {
    return __protocol().gpsOnOff(on);
  }

  /// 开关机
  Future<SettingsResponse> powerOnOff([bool on = true]) {
    return __protocol().powerOnOff(on);
  }

  /// 后退超速报警开关
  Future<SettingsResponse> backwardOverspeedAlterOnOff([bool on = true]) {
    return __protocol().backwardOverspeedAlterOnOff(on);
  }

  /// 两轮车轮毂氛围灯开关
  Future<SettingsResponse> sideWheelLightEffectOnOff([bool on = true]) {
    return __protocol().sideWheelLightEffectOnOff(on);
  }

  /// 设置车辆语音类型
  Future<SettingsResponse> setLanguage(int language) {
    return __protocol().setLanguage(language);
  }

  /// 设置转向灵敏度
  Future<SettingsResponse> setTurningSensitivity(int sensitivity) {
    return __protocol().setTurningSensitivity(sensitivity);
  }

  /// 是否允许关闭安全限速
  bool allowDisableSafeSpeedLimit(ProductProperty productProperty,
      {RealTimeInfo? realTimeInfo,
      HistoryStatistics? statistics,
      TotalStatistics? totalStatistics,
      Settings? settings}) {
    if (isFeatureSupported(Feature.safeSpeedLimit, productProperty.model,
            productProperty.versionWrapper) !=
        1) return false;

    if (productProperty.model.isV13Series()) {
      if (totalStatistics != null) {
        // 大于30km后才可解除
        return (totalStatistics as V13TotalStatistics).mileage.value > 3000;
      }
    }
    return false;
  }

  /// 建立安全连接
  Future buildSecurityConnection() {
    return __protocol().buildSecurityConnection();
  }

  /// 人机版请求重启
  Future<void> requestRebootHmic() {
    return __protocol().requestRebootHmic();
  }

  /// 恢复出厂设置
  Future<SettingsResponse> factoryReset({int level = 0}) {
    return __protocol().factoryReset(level: level);
  }

  /// BMS固定信息
  Future<BMSFixedInfo> requestBMSFixedInfo(int target) {
    return __protocol().requestBMSFixedInfo(target);
  }

  /// BMS电芯电压数据
  Future<AbsBMSCellsVoltage> requestBMSCellsVoltage(int target) {
    return __protocol().requestBMSCellsVoltage(target);
  }

  /// BMS内时间信息
  Future<Datetime> requestBMSDatetime(int target) {
    return __protocol().requestBMSDate(target);
  }

  /// BMS实时信息
  Future<BMSAllRealTimeInfo> requestBMSRealTimeInfo(int target) {
    return __protocol().requestBMSRealTimeInfo(target);
  }

  /// BMS日志管理器
  AbsBmsLogManager createBMSLogManager() {
    return __protocol().createBMSLogManager();
  }

  /// 写入强制更新标识
  Future<SettingsResponse> writeForceUpdate(
      int level, String minVersion, String maxVersion) {
    return __protocol().writeForceUpdate(level, minVersion, maxVersion);
  }

  /// 清除强制升级标识
  Future<SettingsResponse> clearForceUpdate() {
    return __protocol().writeForceUpdate(0, "0.0.0", "0.0.0");
  }

  /// 查询当前固件状态
  /// 是否需要强制升级或是否上次升级中断等
  Future<FirmwareState> requestFirmwareState() {
    return __protocol().requestFirmwareState();
  }

  FwUpdateManager createFwUpdateManager(LinkLayerDeviceHandler handler,
      RequiredManualOperationHandler requiredManualOperationHandler) {
    return __protocol()
        .createFwUpdateManager(handler, requiredManualOperationHandler);
  }

  IFileManager createFileUploadManager(FileConfig config) {
    return __protocol().createFileUploadManager(config);
  }

  SoundFileUploadManager createSoundFileUploadManager() {
    return __protocol().createSoundFileUploadManager();
  }

  LightEffectPkgFileUploadManager createLightEffectFileUploadManager() {
    return __protocol().createLightEffectPkgUploadManager();
  }

  AvatarFileManager createAvatarFileManager() {
    return __protocol().createAvatarFileManager();
  }

  LogFileManager createLogFileManager() {
    return __protocol().createLogFileManager();
  }

  RidingStatisticsHelper createRidingStatisticsHelper() {
    return __protocol().createRidingStatisticsHelper();
  }

  /// 获取音效包ID列表
  Future<List<int>> getSoundPackIdList({int? currentSoundPackId}) {
    return __protocol()
        .getSoundPackIdList(currentSoundPackId: currentSoundPackId);
  }

  /// 删除音效包
  Future<FileResponse> deleteSoundPack(int id) {
    return __protocol().deleteSoundPack(id);
  }

  /// 删除DIY的单条音效
  Future<FileResponse> deleteDiySoundItem(int soundIndex) {
    return __protocol().deleteDiySoundItem(soundIndex);
  }

  /// 获取氛围灯效包ID列表
  Future<List<int>> getLightEffectPkgIdList() {
    return __protocol().getLightEffectPkgIdList();
  }

  /// 删除灯效包
  Future<FileResponse> deleteLightEffectPkg(int id) {
    return __protocol().deleteLightEffectPkg(id);
  }

  /// 获取DIY的单条音效序号列表
  Future<List<int>> getSoundItemIndexList() {
    return __protocol().getSoundItemIndexList();
  }

  /// 获取文件列表
  Future<FileListResponse> getFileList({int diskIndex = 0, Object? filter}) {
    return __protocol().getFileList(filter: filter);
  }

  /// 获取剩余磁盘容量
  Future<int> getRemainStorageCapacity({int diskIndex = 0}) {
    return __protocol().getRemainStorageCapacity(diskIndex: diskIndex);
  }

  /// 停止电机自检
  Future<SettingsResponse> stopMotorSelfCheck() {
    return __protocol().stopMotorSelfCheck();
  }

  /// 停止电机自适应
  Future<SettingsResponse> stopMotorAutoCalibration() {
    return __protocol().stopMotorAutoCalibration();
  }

  /// 清除电机自适应效果
  Future<SettingsResponse> resetMotorAutoCalibrationEffect() {
    return __protocol().resetMotorAutoCalibrationEffect();
  }

  /// 设置加速力度
  /// [type] 前轮/后轮
  Future<SettingsResponse> setAccForce(int force, {int? type}) {
    return __protocol().setAccForce(force, type: type);
  }

  /// 设置电子刹力度
  /// [type] 前轮/后轮
  Future<SettingsResponse> setBrakeForce(int force, {int? type}) {
    return __protocol().setBrakeForce(force, type: type);
  }

  /// 设置自动进入Park模式时间
  Future<SettingsResponse> setParkTime(int seconds) {
    return __protocol().setParkTime(seconds);
  }

  /// 设置单踏板模式开关
  Future<SettingsResponse> onePedalModeOnOff([bool on = true]) {
    return __protocol().onePedalModeOnOff(on);
  }

  /// 设置刹车优先模式开关
  Future<SettingsResponse> brakeFirstModeOnOff([bool on = true]) {
    return __protocol().brakeFirstModeOnOff(on);
  }

  /// 设置最大充电电流
  Future<SettingsResponse> setMaxChargeCurrent(int currentAc220, int currentAc110) {
    return __protocol().setMaxChargeCurrent(currentAc220, currentAc110);
  }

  /// 设置充电截至电量
  Future<SettingsResponse> setChargeLimitPercentage(int percentage) {
    return __protocol().setChargeLimitPercentage(percentage);
  }

  /// 查询某条消息是否为某个设备正在主动请求固件升级
  /// - [msg] 待查询的消息
  /// - return 若[msg]不是主动请求升级的消息，则返回null；否则返回正在主动请求升级设备的设备号
  int? whichDeviceRequestingUpdate(IMessage msg) {
    return Util.whichDeviceRequestingUpdate(msg);
  }

  /// 查询指定车型所有需要安全连接的功能
  List<int> getFeaturesNeedSecurityConnection(
      ProductModel model, VersionWrapper version) {
    if (1 != isFeatureSupported(Feature.securityConnection, model, version)) {
      return [];
    }

    var features = [Feature.lock, Feature.forceFmUpdate, Feature.lostMode];
    if (model.isV12Series() || model.isV13Series()) {
      features.add(Feature.setPassword);
      features.add(Feature.setPasswordType);
    }
    return features;
  }

  Future sendTransparentData(message) {
    return __protocol().sendTransparentData(message);
  }

  /// 查询某功能是否支持
  /// [feature] 功能ID, see [Feature]
  /// return 1 -> 支持; 0 -> 不支持; -1 -> 未知
  static int isFeatureSupported(
      int feature, ProductModel model, VersionWrapper version) {
    // if (version.toString() == VersionWrapper().toString()) return 1;
    switch (feature) {
      case Feature.securityConnection:
        if (model.isLS1Series()) {
          return VersionUtils.higherOrEquals(
                  version.getAppVersionByDevice(Constant.deviceS1Display),
                  "1.3.0")
              ? 1
              : 0;
        }
        if (model.isLorinModel()) return 1;
        return 0;
      case Feature.safeSpeedLimit:
        if (model.isLS1Series()) return 1;
        if (model.isV13Series()) {
          return VersionUtils.higherOrEquals(
                  version.getAppVersionByDevice(Constant.deviceEUCV13HMIC),
                  "2.0.22")
              ? 1
              : 0;
        }
        return 0;
      case Feature.lostMode:
      case Feature.forceFmUpdate:
        if (model.isLS1Series()) {
          return VersionUtils.higherOrEquals(
                  version.getAppVersionByDevice(Constant.deviceS1Display),
                  "1.3.0")
              ? 1
              : 0;
        }
        if (model.isV11()) {
          return VersionUtils.higherOrEquals(
                  version.getAppVersionByDevice(Constant.deviceEUCV11HMIC),
                  "1.1.95")
              ? 1
              : 0;
        }
        if (model.isLR1Series()) {
          return VersionUtils.higherOrEquals(
                  version.getAppVersionByDevice(Constant.deviceLR1Display),
                  "2.2.7")
              ? 1
              : 0;
        }
        if (model.isLE1V2Series()) return 0;
        if (model.isLorinModel()) return 1;
        return 0;
      case Feature.hwVersion:
        if (model.isV11()) {
          if (VersionUtils.lower(
              version.getAppVersionByDevice(Constant.deviceEUCV11HMIC),
              "1.1.95")) return 0;
          return 1;
        }
        if (model.isLS1Series()) {
          if (VersionUtils.lower(
              version.getAppVersionByDevice(Constant.deviceS1Display),
              "1.3.8")) {
            return 0;
          }
          return 1;
        }
        return 1;
    }
    return -1;
  }

  bool supportRequestMtu({String? deviceName, Uint8ClampedList? advData}) {
    if (deviceName == null && advData == null) return false;
    if (advData != null) {
      /// TODO
      return true;
    }
    if (matchesList(deviceName!, ezCANProtocolDeviceNamePrefix)) {
      return false;
    }
    return true;
  }

  Protocol __protocol() {
    if (_protocol == null) {
      throw InitException('You should call preInit() first!');
    }
    return _protocol!;
  }

  /// 根据设备名称[deviceName]或协议标识符[protocolFlag]识别协议类型
  /// 优先根据协议标识符[protocolFlag]识别
  static ProtocolType parseProtocolType(
      {String? deviceName, int? protocolFlag}) {
    if (protocolFlag != null) {
      if (protocolFlag == lorinProtocolFlag) {
        return ProtocolType.lorin;
      }
      if (protocolFlag == ezCANProtocolFlag) {
        return ProtocolType.ezCAN;
      }
      if (protocolFlag == elephantProtocolFlag) {
        return ProtocolType.elephant;
      }
    }

    if (deviceName != null) {
      /*if (RegExp(lorinProtocolDeviceNameRegex).hasMatch(deviceName)) {
                return ProtocolType.lorin;
            }
            if (RegExp(ezCANProtocolDeviceNameRegex).hasMatch(deviceName)) {
                return ProtocolType.ezCAN;
            }
            if (RegExp(elephantProtocolDeviceNameRegex).hasMatch(deviceName)) {
                return ProtocolType.elephant;
            }*/
      if (matchesList(deviceName, lorinProtocolDeviceNamePrefix)) {
        return ProtocolType.lorin;
      }
      if (matchesList(deviceName, ezCANProtocolDeviceNamePrefix)) {
        return ProtocolType.ezCAN;
      }
      if (matchesList(deviceName, elephantProtocolDeviceNamePrefix)) {
        return ProtocolType.elephant;
      }
    }
    throw NotSupportException('Device [$deviceName] is not supported.');
  }

  static Map<String, Object> getDeviceConfig(String deviceName) {
    Map<String, Object> config = {'mtu': 20, 'supportRequestMtu': false};
    if (matchesList(deviceName, ezCANProtocolDeviceNamePrefix)) {
      config['writeWithoutResponse'] = true;
    }
    if (matchesList(deviceName, lorinProtocolDeviceNamePrefix)) {
      config['supportRequestMtu'] = Platform.isAndroid;
      config['mtu'] = Platform.isAndroid ? 235 : 170;
      config['writeWithoutResponse'] = false;
      if (deviceName.startsWith("E20") ||
          deviceName.startsWith("V6") ||
          deviceName.startsWith("E10") ||
      deviceName.startsWith("E15")) {
        config['mtu'] = Platform.isAndroid ? 220 : 170;
        config['writeWithoutResponse'] = true;
      }

      // 早期RS的蓝牙不支持request mtu，但由于无法区分版本，RS均使用默认mtu，不协商
      if (deviceName.startsWith("RS")) config['supportRequestMtu'] = false;
    }
    return config;
  }

  static int?
      guessWhichDeviceFirmwareMayBeBrokenWhenCouldntRetrieveActiveDeviceFromConnection(
          String deviceName,
          {Uint8List? advData}) {
    if (advData != null) {}
    if (deviceName.startsWith("E20") ||
        deviceName.startsWith("V6") ||
        deviceName.startsWith("E10") ||
    deviceName.startsWith("E15")) {
      return DeviceUtils.lorinVBtDevice;
    }
    return null;
  }

  static ProductProperty? simulateProductProperty(String deviceName,
      {Uint8List? advData}) {
    if (advData != null) {}
    if (deviceName.startsWith("E20")) {
      ProductModel model = ProductModel(Uint8(ProductModel.euc),
          Uint8(ProductModel.E20), Uint8(1), Uint8(1), Uint8(1), Uint8(0));
      VersionWrapper versionWrapper = VersionWrapper();
      versionWrapper.put(DeviceUtils.lorinVBtDevice,
          Version(Uint8(DeviceUtils.lorinVBtDevice), "0.0.0", "", ""));
      ProductProperty productProperty = ProductProperty(
          ProductProperty.unknownSn, model, null, versionWrapper);
      return productProperty;
    }
    if (deviceName.startsWith("E10")) {
      ProductModel model = ProductModel(Uint8(ProductModel.euc),
          Uint8(ProductModel.E10), Uint8(1), Uint8(1), Uint8(1), Uint8(0));
      VersionWrapper versionWrapper = VersionWrapper();
      versionWrapper.put(DeviceUtils.lorinVBtDevice,
          Version(Uint8(DeviceUtils.lorinVBtDevice), "0.0.0", "", ""));
      ProductProperty productProperty = ProductProperty(
          ProductProperty.unknownSn, model, null, versionWrapper);
      return productProperty;
    }
    if(deviceName.startsWith("E15")) {
      ProductModel model = ProductModel(Uint8(ProductModel.euc),
          Uint8(ProductModel.E15), Uint8(1), Uint8(1), Uint8(1), Uint8(0));
      VersionWrapper versionWrapper = VersionWrapper();
      versionWrapper.put(DeviceUtils.lorinVBtDevice,
          Version(Uint8(DeviceUtils.lorinVBtDevice), "0.0.0", "", ""));
      ProductProperty productProperty = ProductProperty(
          ProductProperty.unknownSn, model, null, versionWrapper);
      return productProperty;
    }
    if (deviceName.startsWith("V6")) {
      ProductModel model = ProductModel(Uint8(ProductModel.euc),
          Uint8(ProductModel.V6), Uint8(1), Uint8(1), Uint8(1), Uint8(0));
      VersionWrapper versionWrapper = VersionWrapper();
      versionWrapper.put(DeviceUtils.lorinVBtDevice,
          Version(Uint8(DeviceUtils.lorinVBtDevice), "0.0.0", "", ""));
      ProductProperty productProperty = ProductProperty(
          ProductProperty.unknownSn, model, null, versionWrapper);
      return productProperty;
    }
    return null;
  }

  static bool matchesList(String target, List<String> prefixList) {
    for (String prefix in prefixList) {
      if (target.startsWith(prefix)) return true;
    }
    return false;
  }
}
